﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Wheeler.Common.Extensions;
using Wheeler.Domain;
using Wheeler.Web.ViewModels;
using Wheeler.Web.Utility;
using AutoMapper;
using Wheeler.Web.ViewModels.UtilityModels;
using System.IO;
using Excel;
using Wheeler.Common.DB;


namespace Wheeler.Web.Areas.Admin.Controllers
{
    [Authorize(Roles="Admin")]
    public class FixedVehicleController : BaseController
    {
		private WheelerEntities _Context = new WheelerEntities();
        
		#region Constructors
		public FixedVehicleController()
		{
		}

		public FixedVehicleController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods

        public ActionResult Index()
        {
            return RedirectToAction("Import");
        }

		public ActionResult Import()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Import(HttpPostedFileBase excelFile)
        {
            if(excelFile.ContentLength <= 0 || !WebUtil.IsValidExcelFile(Path.GetExtension(excelFile.FileName)))
            {
                ModelState.AddModelError("ExcelFile_Cosmetic", "Please Upload a Valid Excel File.");
                return View();
            }
            
            String filePath = Server.MapPath("/Temp");
            if(!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            
            filePath = Path.Combine(filePath, Path.GetFileName(excelFile.FileName));

            excelFile.SaveAs(filePath);

            String message = ImportVehiclesFromExcel(filePath);
            return View((object)message);
        }
        
		#endregion Action Methods
		
		#region Helper Methods

        /// <summary>
        /// Imports Vehicles into the Database. Duplicate check has been done in backend
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private String ImportVehiclesFromExcel(string filePath)
        {
            DataSet ds = ReadFromExcel(filePath);
            if (ds != null)
            {
                DataTable dt = ds.Tables[0];                
                String fileName = Path.GetFileName(filePath);
                UtilityDAO dao = new UtilityDAO();
                String result = dao.ImportFixedVehicles(dt, fileName, LoggedInUser.ID);
                String[] parts = result.Split('|');
                return String.Format("Total Record:{0}<br/>Imported: {1}<br/>Bad Record: {2}<br/>Duplicate: {3}", (dt.Rows.Count - 1), parts[0], parts[2], parts[1]);
            }
            return "Could not find any record to import.";
        }

        /// <summary>
        /// Reads a Given Excel file and returns a DataSet
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected DataSet ReadFromExcel(String filePath)
        {
            //String filePath = _SpFnSetupFilePath;
            IExcelDataReader excelReader = null;
            DataSet ds = new DataSet("FixedVehicles");
            FileStream stream = null;
            try
            {
                stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read);
                if (String.Compare(Path.GetExtension(filePath), ".xls", true) == 0)
                    excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                else if (String.Compare(Path.GetExtension(filePath), ".xlsx", true) == 0)
                    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

                if (excelReader != null)
                {
                    excelReader.IsFirstRowAsColumnNames = true;
                    ds = excelReader.AsDataSet();
                }
            }
            catch (Exception ex)
            {
                String message = String.Format("Could not read the Defination file located in {0}{1}Error Message: {2}", filePath, Environment.NewLine, ex.Message);                
            }
            finally
            {
                if (excelReader != null && !excelReader.IsClosed)
                    excelReader.Close();
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return ds;
        }
		
        #endregion			
    }
}


